<template>
  <view class="stats-page">
    <!-- Mock 测试入口 -->
    <view class="mock-test-entry" v-if="showMockEntry">
      <button class="mock-test-btn" @click="goToMockTest">
        <text class="mock-test-icon">🧪</text>
        <text class="mock-test-text">Mock 数据测试</text>
      </button>
    </view>

    <scroll-view scroll-y class="main-content">
      <!-- Habits Stats -->
      <view class="section">
        <text class="section-title "><text class="section-icon fas fa-check-double" /><text>习惯统计</text></text>
        <view class="grid-2-cols">
          <view class="stat-card">
            <text class="stat-label">总习惯数</text>
            <text class="stat-value">5</text>
          </view>
          <view class="stat-card">
            <text class="stat-label">今日完成率</text>
            <text class="stat-value primary-color">60%</text>
          </view>
          <view class="stat-card col-span-2">
            <text class="stat-label-small">本周习惯打卡趋势</text>
            <view style="height: 206rpx;">
              <l-echart ref="habitsTrendChart" />
            </view>
          </view>
        </view>
      </view>

      <!-- Todos Stats -->
      <view class="section">
        <text class="section-title"><uni-icons type="list" color="#6366F1" size="20"></uni-icons> 待办统计</text>
        <view class="grid-2-cols">
          <view class="stat-card">
            <text class="stat-label">今日待办</text>
            <text class="stat-value">3 <text class="text-sm">/ 5</text></text>
          </view>
          <view class="stat-card">
            <text class="stat-label">本周完成数</text>
            <text class="stat-value secondary-color">12</text>
          </view>
        </view>
      </view>

      <!-- Finance Stats -->
      <view class="section">
        <text class="section-title"><uni-icons type="wallet-filled" color="#EC4899" size="20"></uni-icons> 财务状况分析</text>
        <view class="grid-1-2-cols">
          <view class="stat-card col-span-all">
            <text class="stat-label-small">月度现金流趋势 (近6个月)</text>
            <view style="height: 206rpx;">
              <l-echart ref="cashflowTrendChart" />
            </view>
          </view>
          <view class="stat-card">
            <text class="stat-label-small">资产构成</text>
            <view style="height: 732rpx;">
              <l-echart ref="assetCompositionChart" />
            </view>
          </view>
          <view class="stat-card">
            <text class="stat-label-small">收入来源 (本月)</text>
            <view style="height: 600rpx;">
            <l-echart ref="incomeSourceChart" />
          </view>
          </view>
          <view class="stat-card col-span-all">
            <text class="stat-label-small">负债明细</text>
            <view style="height: 248rpx;">
            <l-echart ref="liabilityDetailsChart" />
          </view>
          </view>
        </view>
        <image src="/static/images/analytics.jpg"
          mode="widthFix" class="section-image" />
      </view>

      <!-- Time Management Stats -->
      <view class="section">
        <text class="section-title"><uni-icons type="watch-filled" color="#F59E0B" size="20"></uni-icons> 时间管理统计</text>
        <view class="grid-1-2-cols">
          <view class="stat-card">
            <text class="stat-label">今日专注时长</text>
            <text class="stat-value">3h 45m</text>
          </view>
          <view class="stat-card">
            <text class="stat-label">本周总记录时长</text>
            <text class="stat-value yellow-color">25h 10m</text>
          </view>
          <view class="stat-card col-span-all">
            <text class="stat-label-small">时间分配 (本周)</text>
          <view style="height: 622rpx;">
            <l-echart ref="timeDistributionChart" />
          </view>
          </view>
          <view class="stat-card col-span-all">
            <text class="stat-label-small">主要活动时长 (本周)</text>
            <view style="height: 248rpx; position: relative">
              <l-echart ref="activityDurationChart" />
            </view>

          </view>
        </view>
        <image src="/static/images/time-management.jpg"
          mode="widthFix" class="section-image" />
      </view>
    </scroll-view>

  </view>
</template>

<script>
// nvue 不需要引入
// #ifdef VUE2
import * as echarts from '@/uni_modules/lime-echart/static/echarts.min';
// #endif
// #ifdef VUE3
// #ifdef MP
// 由于vue3 使用vite 不支持umd格式的包，小程序依然可以使用，但需要使用require
const echarts = require('../../static/echarts.min');
// #endif
// #ifndef MP
// 由于 vue3 使用vite 不支持umd格式的包，故引入npm的包
import * as echarts from 'echarts/dist/echarts.esm';
// #endif
// #endif

export default {
  name: 'StatsIndex',
  data() {
    return {
      // Chart refs will be handled through $refs
      showMockEntry: false
    }
  },
  onLoad() {
    // 检查是否为开发环境，显示Mock测试入口
    // #ifdef H5
    this.showMockEntry = process.env.NODE_ENV === 'development'
    // #endif
    // #ifndef H5
    this.showMockEntry = true // 在非H5环境下也显示，方便测试
    // #endif
  },
  // 处理导航栏按钮点击事件
    onNavigationBarButtonTap(e) {
      if (e.index === 0) { // 设置按钮
        this.goToSettings();
      }
    },
  methods: {
    goToSettings() {
      uni.navigateTo({
        url: '/pages/settings/index'
      });
    },
    
    goToMockTest() {
      uni.navigateTo({
        url: '/pages/test-mock/index'
      });
    },

    

    navigateTo(url) {
      uni.redirectTo({
        url: url
      });
    }

  },
  onReady() {
    // Habits Trend Chart
    // this.$refs.habitsTrendChart.init && this.$refs.habitsTrendChart.init(echarts => {

    //   echarts.setOption(option);
    // });



    setTimeout(async () => {
      if (!this.$refs.habitsTrendChart) return
      const myChart = await this.$refs.habitsTrendChart.init(echarts)
      const option = {
        xAxis: {
          type: 'category',
          data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { fontSize: 10 },
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          min: 0,
          max: 6,
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { show: true, fontSize: 10 },
          splitLine: { lineStyle: { type: 'dashed' } }
        },
        series: [{
          name: '打卡数',
          type: 'line',
          data: [3, 2, 4, 3, 5, 4, 3],
          smooth: 0.5, // 平滑度（对应 tension）
          lineStyle: { color: '#10B981', width: 3 },
          itemStyle: { color: '#10B981' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(16, 185, 129, 0.8)' }, // 起始颜色，80% 不透明度
                { offset: 1, color: 'rgba(16, 185, 129, 0)' }  // 结束颜色，完全透明
              ]
            }
          },
          symbol: 'circle',
          symbolSize: 6
        }],
        grid: { top: 20, right: 10, bottom: 20, left: 15 },
        tooltip: { trigger: 'axis' }
      };
      myChart.setOption(option)
    }, 300)



    // Cashflow Trend Chart
    setTimeout(async () => {
      if (!this.$refs.cashflowTrendChart) return
      const myChart = await this.$refs.cashflowTrendChart.init(echarts)
      const option = {
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月'],
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { fontSize: 10 },
          boundaryGap: false
        },
        yAxis: {
          type: 'value',
          min: 0,
          // max: 6,
          axisLine: { show: false },
          axisTick: { show: false },
          axisLabel: { show: true, fontSize: 10 },
          splitLine: { lineStyle: { type: 'dashed' } }
        },
        series: [{
          name: '月现金流',
          type: 'line',
          data: [2500, 2800, 3200, 3000, 4500, 6500],
          smooth: 0.5, // 平滑度（对应 tension）
          lineStyle: { color: '#10B981', width: 3 },
          itemStyle: { color: '#10B981' },
          areaStyle: {
            color: {
              type: 'linear',
              x: 0, y: 0, x2: 0, y2: 1,
              colorStops: [
                { offset: 0, color: 'rgba(16, 185, 129, 0.8)' }, // 起始颜色，80% 不透明度
                { offset: 1, color: 'rgba(16, 185, 129, 0)' }  // 结束颜色，完全透明
              ]
            }
          },
          symbol: 'circle',
          symbolSize: 6
        }],
        grid: { top: 20, right: 10, bottom: 20, left: 40 },
        tooltip: { trigger: 'axis' }
      };
      myChart.setOption(option)
    }, 300)



    // Asset Composition Chart
    setTimeout(async () => {
      if (!this.$refs.assetCompositionChart) return
      const myChart = await this.$refs.assetCompositionChart.init(echarts)
      const option = {
        tooltip: { trigger: 'item' },
        legend: { bottom: '1%', left: 'center' },
        series: [
          {
            name: '资产构成',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 80000, name: '房地产', itemStyle: { color: '#22D3EE' } },
              { value: 40000, name: '股票基金', itemStyle: { color: '#A78BFA' } },
              { value: 25000, name: '现金储蓄', itemStyle: { color: '#34D399' } },
              { value: 5000, name: '其他投资', itemStyle: { color: '#FBBF24' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option)
    }, 300)



    // Income Source Chart
    setTimeout(async () => {
      if (!this.$refs.incomeSourceChart) return
      const myChart = await this.$refs.incomeSourceChart.init(echarts)
      const option = {
        tooltip: { trigger: 'item' },
        legend: { bottom: '1%', left: 'center' },
        series: [
          {
            name: '收入来源',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: { show: false },
            data: [
              { value: 8800, name: '主动收入 (工资)', itemStyle: { color: '#6366F1' } },
              { value: 1000, name: '被动收入 (房租)', itemStyle: { color: '#10B981' } },
              { value: 200, name: '被动收入 (股息)', itemStyle: { color: '#059669' } }
            ]
          }
        ]
      };
      myChart.setOption(option)
    }, 300)



    // Liability Details Chart
    setTimeout(async () => {
      if (!this.$refs.liabilityDetailsChart) return
      const myChart = await this.$refs.liabilityDetailsChart.init(echarts)
      const option = {
        xAxis: { type: 'value' },
        yAxis: {
          type: 'category',
          data: ['房贷', '车贷', '信用卡']
        },
        series: [
          {
            name: '负债金额',
            type: 'bar',
            data: [
              { value: 35000, itemStyle: { color: '#F87171' } },
              { value: 10000, itemStyle: { color: '#FB923C' } },
              { value: 5000, itemStyle: { color: '#FACC15' } }
            ]
          }
        ],
        grid: { left: '1%', right: '1%', bottom: '3%', containLabel: true }
      };
      myChart.setOption(option)
    }, 300)



    // Time Distribution Chart
    setTimeout(async () => {
      if (!this.$refs.timeDistributionChart) return
      const myChart = await this.$refs.timeDistributionChart.init(echarts)
      const option = {
        tooltip: { trigger: 'item' },
        legend: { bottom: '1%', left: 'center' },
        series: [
          {
            name: '时间分配',
            type: 'pie',
            radius: '50%',
            data: [
              { value: 10, name: '工作', itemStyle: { color: '#3B82F6' } },
              { value: 5, name: '学习', itemStyle: { color: '#10B981' } },
              { value: 3, name: '运动', itemStyle: { color: '#F59E0B' } },
              { value: 2, name: '通勤', itemStyle: { color: '#6366F1' } },
              { value: 2.5, name: '家务', itemStyle: { color: '#EC4899' } },
              { value: 2.5, name: '娱乐', itemStyle: { color: '#84CC16' } }
            ],
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      myChart.setOption(option)
    }, 300)



    // Activity Duration Chart
    setTimeout(async () => {
      if (!this.$refs.activityDurationChart) return
      const myChart = await this.$refs.activityDurationChart.init(echarts)
      const option = {
        xAxis: { type: 'value' },
        yAxis: {
          type: 'category',
          data: ['项目A', '专业课程', '健身房', '阅读', '编码']
        },
        series: [
          {
            name: '活动时长 (小时)',
            type: 'bar',
            data: [
              { value: 8, itemStyle: { color: '#0EA5E9' } },
              { value: 4, itemStyle: { color: '#22C55E' } },
              { value: 2.5, itemStyle: { color: '#F97316' } },
              { value: 2, itemStyle: { color: '#8B5CF6' } },
              { value: 3.5, itemStyle: { color: '#D946EF' } }
            ]
          }
        ],
        grid: { left: 0, right: '1%', bottom: '3%', containLabel: true }
      };
      myChart.setOption(option)
    }, 300)


  }
}
</script>

<style lang="scss" scoped>
@import '@/static/css/fontawesome.min.css';
@import '@/static/css/brands.min.css';
@import '@/static/css/solid.min.css';

.stats-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #FFFFFF;
  /* base-100-light */
  color: #1F2937;
  /* base-content-light */
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
}

.main-content {
  flex: 1;

  overflow-y: auto;
  width: auto;
  /* Adjust padding-top to account for fixed uni-nav-bar height */
  // padding-top: calc(44px + env(safe-area-inset-top));
}

.section {
  // margin-bottom: 20px;
  padding: 15px;
}

.section-title {
  font-size: 36rpx;
  font-weight: 500;
  color: #6B7280;
  /* text-muted-light */
  margin-bottom: 24rpx;
  display: inline-block;
  align-items: center;
  position: relative;
  width: 100%;

  uni-icons {
    margin-right: 8px;
  }

  .section-icon {
    font-size: 36rpx;

    width: 32rpx;
    height: 32rpx;
    border-radius: 8px;
    display: inline-block;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    color: rgb(16, 185, 129)
  }
}



.grid-2-cols {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 15px;
}

.grid-1-2-cols {
  display: grid;
  grid-template-columns: repeat(1, 1fr);
  gap: 15px;

  @media (min-width: 768px) {
    grid-template-columns: repeat(2, 1fr);
  }
}

.col-span-2 {
  grid-column: span 2 / span 2;
}

.col-span-all {
  grid-column: 1 / -1;
}

.stat-card {
  background-color: #F3F4F6;
  /* neutral-light */
  padding: 32rpx;
  border-radius: 8px;

  --tw-shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1);
  --tw-shadow-colored: 0 1px 3px 0 var(--tw-shadow-color), 0 1px 2px -1px var(--tw-shadow-color);
  box-shadow: var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow);
}

.stat-label {
  display: block;
  font-size: 14px;
  color: #6B7280;
  /* text-muted-light */
}

.stat-label-small {
  font-size: 28rpx;
  color: #6B7280;
  /* text-muted-light */
  margin-bottom: 5px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1F2937;
  /* base-content-light */
  margin-top: 5px;
}

.primary-color {
  color: #10B981;
  /* primary */
}

.secondary-color {
  color: #6366F1;
  /* secondary */
}

.yellow-color {
  color: #F59E0B;
  /* yellow-500 */
}

.section-image {
  width: 100%;
  height: 130px;
  border-radius: 8px;
  margin-top: 15px;
  opacity: 0.75;
}

/* Mock 测试入口样式 */
.mock-test-entry {
  padding: 15px;
  background-color: #FEF3C7;
  border-bottom: 1px solid #F59E0B;
}

.mock-test-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #F59E0B;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 12px 20px;
  font-size: 14px;
  font-weight: 500;
  width: 100%;
  transition: background-color 0.2s;
}

.mock-test-btn:active {
  background-color: #D97706;
}

.mock-test-icon {
  margin-right: 8px;
  font-size: 16px;
}

.mock-test-text {
  color: white;
  font-size: 14px;
  font-weight: 500;
}

</style>